#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
typedef struct node
{
	int data;
	struct node* next;


}node;
node* BuySListNode(int x)
{
	node* newnode = (node*)malloc(sizeof(node));
	if (newnode == NULL)
	{
		perror("malloc fail");
	}
	newnode->next = NULL;
	newnode->data = x;
	return newnode;
}
void pushback(node** pphead, int x)
{
	node* newnode = BuySListNode(x);
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
		node* cur = *pphead;
		while (cur->next != NULL)
		{
			cur = cur->next;



		}
		cur->next = newnode;





	}







}
void  printdata(node* phead)
{
	node* cur = phead;
	while (cur)
	{
		printf("%d ", cur->data);
		cur = cur->next;

	}




}
void pushFront(node** pphead, int x)
{
	node* newnode = BuySListNode(x);
	newnode->next = *pphead;
	*pphead = newnode;
		
}
void popFront(node** pphead)
{
	node* next = (*pphead)->next;
	free(*pphead);
	*pphead = next;




}
void popBack(node** pphead)
{
	node* cur = *pphead;
	node* prev = NULL;
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		
	}
	else
	{



		while (cur->next != NULL)
		{
			prev = cur;
			cur = cur->next;
		}
		free(cur);
		prev->next = NULL;





	}



}
node* SListFind(node* pphead, int x)
{
	node* cur = pphead;
	while (cur->data != x)
	{
		cur = cur->next;
	}
	return cur;




}
void SeqListInsert(node** pphead, node* pos, int x)
{
	node* newnode = BuySListNode(x);
	if (pos == *pphead)
	{
		pushFront(pphead, x);
	}
	

	else
	{node* prev = NULL;
	 node* cur = *pphead;
		while (cur!= pos)
		{
			prev = cur;
			cur = cur->next;
		}
		newnode->next = cur;
		prev->next = newnode;




	}



}
void SeqListErase(node** pphead, node* pos)
{
	node* next = pos->next;
	node* cur = *pphead;
	while (cur->next != pos)
	{
		cur = cur->next;
	}
	cur->next = next;
	free(pos);



}
void SListInsertAfter(node* pos, int x)
{
	node* newnode = BuySListNode(x);
	if (pos->next == NULL)
	{
		
		pos->next = newnode;

		


	}
	else
	{

		node* next = pos->next;
		newnode->next = next;
		pos->next = newnode;


	}



}
void SListEraseAfter(node* pos)
{
	if (pos->next == NULL)
		return;
	else
	{
		node* next = pos->next;
		pos->next = next->next;
		free(next);



	}



}

int main()
{
	node* n1 = (node*)malloc(sizeof(node));
	node* n2 = (node*)malloc(sizeof(node));
	node* n3 = (node*)malloc(sizeof(node));
	node* n4 = (node*)malloc(sizeof(node));
	n1->data = 1;
	n2->data = 2;
	n3->data = 3;
	n4->data = 4;

	n1->next = n2;
	n2->next = n3;
	n3->next = n4;
	n4->next = NULL;
	pushback(&n1, 5);
	pushback(&n1, 6);
	pushback(&n1, 7);
	/*pushFront(&n1, 1000);
	popFront(&n1);*/
	popBack(&n1);
	SeqListInsert(&n1, SListFind(n1, 5), 100000);
	SListInsertAfter(SListFind(n1, 5), 50000);
	SListEraseAfter(SListFind(n1, 5));
	printdata(n1);
	//printf("%d", SListFind(n1, 5)->data);

}